﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace GetAssemblyInfo
{
    class Program
    {
        public enum EXITCODES
        {
            SUCCESS,
            ASSEMBLY_NOT_FOUND
        }

        static void Main(string[] args)
        {
            if (args.Length < 1 || args[0].ToString().Contains("?"))
            {
                PrintHelp();
                Environment.Exit((int)EXITCODES.SUCCESS);
            }
            else
            {
                string asmName = args[0].ToString();
                string retFormat;
                if (args.Length > 1)
                {
                    retFormat = args[1].ToString();
                }
                else
                {
                    // default format
                    retFormat = "AssemblyNamevMajor.vMinor.vBuild";
                }
                
                if (System.IO.File.Exists(asmName))
                {
                    
                    // now get an external assembly
                    AssemblyName anm = AssemblyName.GetAssemblyName(asmName);
                    Version versionInfo = anm.Version;
                    StringBuilder sb = new StringBuilder();
                    sb.Append(retFormat);
                    sb.Replace("vMajor", versionInfo.Major.ToString());
                    sb.Replace("vMinor", versionInfo.Minor.ToString());
                    sb.Replace("vBuild", versionInfo.Build.ToString());
                    sb.Replace("FullName", anm.FullName.ToString());
                    sb.Replace("AssemblyName", anm.Name.ToString());
                    
                    // and show its version
                    Console.WriteLine(sb.ToString());
                    Environment.Exit((int)EXITCODES.SUCCESS);
                }
                else
                {
                    // no exist
                    Console.WriteLine("NOT EXIST");
                    Environment.Exit((int)EXITCODES.ASSEMBLY_NOT_FOUND);
                }
            }

            
        }

        static void PrintHelp()
        {
            // get the version object for this assembly
            Version v = System.Reflection.Assembly.GetExecutingAssembly().
             GetName().Version;
            // write out the whole version number
            Console.WriteLine(v.ToString());
            // or do it in pieces
            Console.WriteLine(v.Major + "." + v.Minor + "." + v.Build +
             "." + v.Revision);

            
            Console.WriteLine("Usage: ");
            Console.WriteLine("----------------");
            Console.WriteLine("GetAssemblyInfo \"assemblyfile\" \"return formatstring\"");
            Console.WriteLine("\r\nExample:\r\nGetAssemblyInfo \"myapp.exe\" \"AssemblyNamevMajor.vMinor.vBuild\" ");
        }
    }
}
